package com.example.hoasbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hoasbackend.common.IndentOperationType;
import com.example.hoasbackend.common.IndentState;
import com.example.hoasbackend.common.utls.DateTimeUtil;
import com.example.hoasbackend.common.utls.RedisUtil;
import com.example.hoasbackend.model.domain.Indent;
import com.example.hoasbackend.mapper.IndentMapper;
import com.example.hoasbackend.model.domain.IndentOperation;
import com.example.hoasbackend.model.domain.RoomType;
import com.example.hoasbackend.model.AO.CreateIndentBatchAO;
import com.example.hoasbackend.model.dto.IndentRedis;
import com.example.hoasbackend.service.IndentOperationService;
import com.example.hoasbackend.service.IndentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hoasbackend.service.RoomTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lhx
 * @since 2022-03-03
 */
@Service
public class IndentServiceImpl extends ServiceImpl<IndentMapper, Indent> implements IndentService {
    @Autowired
    RoomTypeService roomTypeService;
    @Autowired
    IndentService indentService;
    @Autowired
    IndentOperationService indentOperationService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    DateTimeUtil dateTimeUtil;

    @Override
    public Indent turnCreateIndentBatchAOToIndent(CreateIndentBatchAO createIndentBatchAO, long userId,long batchId) {
        Indent indent=new Indent();
        RoomType roomType=roomTypeService.getById(createIndentBatchAO.getRoomTypeId());
        indent.setUserId(userId);
        indent.setRoomtypeId(createIndentBatchAO.getRoomTypeId());
        indent.setBatchId(batchId);
        indent.setDescription(roomType.getType()+" "+roomType.getBedType());
        indent.setAmount(roomType.getPrice());
        return indent;
    }

    @Override
    public List<Indent> splitIndentBatch(Indent indentBasicInfo, long roomNum) {
        List<Indent>indentBatch =new ArrayList<>();
//        System.out.println("here");
        int i=0;
        for (i=0;i<roomNum;++i){
            indentBatch.add(new Indent(indentBasicInfo));
        }
        return indentBatch;
    }

    /**
     * 2.1存储indent
     * 2.2创建indentOperation
     *  2.3设定checkinout日期
     * @param indent
     * @param checkInTime
     * @param checkOutTime
     */
    @Override
    public void createIndent(Indent indent, String checkInTime, String checkOutTime) {

//        indentService.saveRedis(indent,checkInTime,checkOutTime, IndentState.CREATED, RedisUtil.INDENT_EXPIRATION_TIME);
        indentService.save(indent);
        indentOperationService.createIndentOperation(
                indent.getId(),IndentOperationType.CREATE,checkInTime+";"+checkOutTime,
                indent.getUserId(),indent.getUserId());
    }

    @Override
    public List<Indent> getListByBatchId(long batchId) {
        QueryWrapper<Indent> indentQueryWrapper=new QueryWrapper<>();
        indentQueryWrapper.eq("batch_id",batchId);
        List<Indent> result = indentService.list(indentQueryWrapper);
        return result;
    }

    @Override
    public Double getTotalAmount(List<Indent> indentBatch) {
        Double totalAmount=0D;
        for(Indent indent:indentBatch){
            totalAmount+=indent.getAmount();
        }
        return totalAmount;

    }

    @Override
    public String getIndentState(Long indentId) {
        Indent indent=indentService.getById(indentId);
        Long batchId=indent.getBatchId();
        //try to get from redis
        String indentState=redisUtil.get(batchId+":state");
        if(!indentState.equals(null)){
            return indentState;
        }

//        refresh the redis of this indent
        IndentRedis indentRedis=indentService.getIndentRedis(indent);
        indentService.saveRedisIndent(indentRedis);
//        get again
        indentState=redisUtil.get(batchId+":state");
        return indentState;
    }

    @Override
    public void saveRedisIndent(IndentRedis indentRedis) {
        Long batchId=indentRedis.getIndentBatchId();
        redisUtil.set(batchId+"","CountingDown",indentRedis.getExpirationTime());
        redisUtil.set(batchId+":checkintime",dateTimeUtil.dateTimetoString(indentRedis.getCheckInTime()));
        redisUtil.set(batchId+":checkouttime",dateTimeUtil.dateTimetoString(indentRedis.getCheckOutTime()));
        redisUtil.set(batchId+":state",indentRedis.getState());

    }

    @Override
    public IndentRedis getIndentRedis(Indent indent) {
        long batchId=indent.getBatchId();
        LocalDateTime checkInTime=indentOperationService.getCheckInTime(indent.getId());;
        LocalDateTime checkOutTime=indentOperationService.getCheckOutTime(indent.getId());
        String state=indentService.getMysqlIndentState(indent.getId());
        long expirationTime=indentOperationService.getExpirationDuration(batchId,state);

        return new IndentRedis(batchId,checkInTime,checkOutTime,expirationTime,state);
    }

    @Override
    public String getMysqlIndentState(Long indentId) {
        IndentOperation indentOperation = new IndentOperation();
        long lastOpType = indentOperationService.getLastOperationType(indentId);
        LocalDateTime checkInTime = indentOperationService.getCheckInTime(indentId);
        LocalDateTime checkOutTime = indentOperationService.getCheckOutTime(indentId);
        LocalDateTime now = LocalDateTime.now();
        String state="";
        if (lastOpType == IndentOperationType.CREATE) {
            state = IndentState.CREATED;
        } else if (lastOpType == IndentOperationType.CANCEL) {
            state = IndentState.CANCELED;
        } else if (lastOpType == IndentOperationType.PAY) {
            if (now.compareTo(checkInTime) < 0) {
                state = IndentState.PAID;
            } else if (now.compareTo(checkInTime) > 0 && now.compareTo(checkOutTime) < 0) {
                state = IndentState.CHECKEDIN;
            } else state = IndentState.CHECKEDOUT;
        } else if (lastOpType == IndentOperationType.COMMENT) {
            state = IndentState.COMMENTED;
        }
        return state;
    }




}
